<?php


 function checkAuth()
{
    $flag = true;
    $username = M('admin')->where(['id'=>session('uid')])->getField('username');

    $salt = C("COOKIE_SALT");
    $ip = get_client_ip();
    $auth = password(session('uid').$username.$ip.$salt);
    if($auth != cookie('auth')){
        $flag = false;
    }

    return $flag;
}
function get_url() {
    $sys_protocal = isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == '443' ? 'https://' : 'http://';
    $php_self = $_SERVER['PHP_SELF'] ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME'];
    $path_info = isset($_SERVER['PATH_INFO']) ? $_SERVER['PATH_INFO'] : '';
    $relate_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : $php_self.(isset($_SERVER['QUERY_STRING']) ? '?'.$_SERVER['QUERY_STRING'] : $path_info);
    return $sys_protocal.(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '').$relate_url;
}

 function getMenu($items, $id = "id", $pid = "pid", $son = "children"){
    $tree = array();
    $tmpMap = array();
    foreach($items as $item){
        if($item["pid"] == 0){
            $father_ids[] = $item["id"];
        }
    }
    foreach ($items as $item){
        $tmpMap[$item[$id]] = $item;
    }
    foreach ($items as $item){
        if($item["pid"] <> 0 && !in_array($item["pid"], $father_ids)){
            continue;
        }
        if (isset($tmpMap[$item[$pid]])){
            $tmpMap[$item[$pid]][$son][] = & $tmpMap[$item[$id]];
        }else{
            $tree[] = & $tmpMap[$item[$id]];
        }
    }
    return $tree;
}

function ajax_return($code,$msg,$data=[])
{


    $ajax['code'] = $code;
    $ajax['msg'] = $msg;
    $ajax['data'] = $data;
    exit(json_encode($ajax));
}


function build_order_no(){
    return date('ymdHis').substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}


function get_between($str,$flag, $start, $end) {
	
	$substr = substr($str, str_n_pos($str,$flag,$start)+1,(str_n_pos($str,$flag,$end)-1)-(str_n_pos($str,$flag,$start)));
	if($substr) return $substr;

}
/**
* 查找字符串第n次出现的位置 
*/
function str_n_pos($str,$find,$n){
	for ($i=1;$i<=$n;$i++){
		$pos = strpos($str,$find);
		$str = substr($str,$pos+1);
		$pos_val=$pos+$pos_val+1;
	}
	return $pos_val-1;
}
//发送模板消息
# $touser 接收者（用户）的 openid
# $template_id 所需下发的模板消息的id
# $page 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转
# form_id 表单提交场景下，为 submit 事件带上的 formId；支付场景下，为本次支付的 prepay_id
# $arr_data 发送的内容 数组
# $emphasis_keyword 放大的关键词，格式：'keyword1.DATA'
# $color 模板内容字体的颜色，不填默认黑色
function send_msg($at,$form_id,$touser,$template_id,$page,$arr_data=array(),$emphasis_keyword='',$color=''){

	$url = 'https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token='.$at;
	$dd['touser']=$touser;
	$dd['template_id']=$template_id;
	$dd['page']=$page;  //点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,该字段不填则模板无跳转。
	$dd['form_id']=$form_id;
	$dd['data']=$arr_data;                        //模板内容，不填则下发空模板
	//$dd['color']=$color;                        //模板内容字体的颜色，不填默认黑色
	$dd['emphasis_keyword']=$emphasis_keyword;    //模板需要放大的关键词，不填则默认无放大
   // dump(https_curl_json($url,$dd,'json'));die;
    $result = https_curl_json($url,$dd,'json');

        return $result;
   // file_put_contents('gg.txt',json_encode($result));
}


//导出订单
function exportExcel($expTitle,$expCellName,$expTableData){
    $xlsTitle = iconv('utf-8', 'gb2312', $expTitle);//文件名称
    $fileName = $expTitle;//or $xlsTitle 文件名称可根据自己情况设定
    $cellNum = count($expCellName);
    $dataNum = count($expTableData);
    vendor("PHPExcel.PHPExcel");
    $objPHPExcel = new PHPExcel();
    $cellName = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ','AR','AS','AT','AU','AV','AW','AX','AY','AZ');

    $objPHPExcel->getActiveSheet(0)->mergeCells('A1:'.$cellName[$cellNum-1].'1');//合并单元格
    $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A1', $expTitle.'  Export time:'.date('Y-m-d H:i:s'));
    for($i=0;$i<$cellNum;$i++){
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue($cellName[$i].'2', $expCellName[$i][1]);
    }
    // Miscellaneous glyphs, UTF-8
    for($i=0;$i<$dataNum;$i++){
        for($j=0;$j<$cellNum;$j++){
            $objPHPExcel->getActiveSheet(0)->setCellValue($cellName[$j].($i+3), $expTableData[$i][$expCellName[$j][0]]);
        }
    }

    header('pragma:public');
    header('Content-type:application/vnd.ms-excel;charset=utf-8;name="'.$xlsTitle.'.xls"');
    header("Content-Disposition:attachment;filename=$fileName.xls");//attachment新窗口打印inline本窗口打印
    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
    $objWriter->save('php://output');
    $objWriter->save('../');
    exit;
}








function getAccessToken($appid,$appkey)
{
    $acc = S('access_token_'.$appid);
    $at = $acc['access_token'];
    if(!$at ||  (time() - $acc['dateline']) > 7200){ //不存在或者已经失效


        $res=https_request("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appkey);#获取access_token
        $res=json_decode($res,true);
        if($res){
            $data['dateline'] = time();
            $data['access_token'] = $res['access_token'];
            $at = $data['access_token'] = $res['access_token'];
            S('access_token_'.$appid,$data,7200);
        }


    }

    return $at;
}


//CURL POST请求
function https_curl_json($url,$data,$type){
	if($type=='json'){//json $_POST=json_decode(file_get_contents('php://input'), TRUE);
		$headers = array("Content-type: application/json;charset=UTF-8","Accept: application/json","Cache-Control: no-cache", "Pragma: no-cache");
		$data=json_encode($data,JSON_UNESCAPED_UNICODE);
	}


	//dump($data);die;
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_URL, $url);
	curl_setopt($curl, CURLOPT_POST, 1); // 发送一个常规的Post请求
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
	if (!empty($data)){
		curl_setopt($curl, CURLOPT_POST, 1);
		curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
	}
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($curl, CURLOPT_HTTPHEADER, $headers );
	$output = curl_exec($curl);
	if (curl_errno($curl)) {
		return curl_error($curl);//捕抓异常
	}
	curl_close($curl);
	return $output;
}
//以万为单位转换
function FormatMoney($money){
	if($money >= 10000){
	 return sprintf("%.2f", $money/10000).'万';
	}else{
	 return $money;
	}
}
//关键词过滤
function not_allow_words($str){
	$not_allow_words=explode('|',trim(C('not_allow_words')));
	
	foreach($not_allow_words as $nwords){
		if(strpos($str, $nwords)!==false){
			return true;
		}
	}
	return false;
}
//将xml格式转换成数组  
function xmlToArray($xml) {  
	//禁止引用外部xml实体   
	libxml_disable_entity_loader(true);  
	$xmlstring = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);  
	$val = json_decode(json_encode($xmlstring), true);  
	return $val;  
}
// curl请求
function http_request($url,$timeout=30,$header=array()){
        if (!function_exists('curl_init')) {
            throw new Exception('server not install curl');  
        }  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        curl_setopt($ch, CURLOPT_HEADER, true);  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);  
        if (!empty($header)) {  
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  
        }  
        $data = curl_exec($ch);
        list($header, $data) = explode("\r\n\r\n", $data);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);


        if ($http_code == 301 || $http_code == 302) {  
            $matches = array();  
            preg_match('/Location:(.*?)\n/', $header, $matches);  
            $url = trim(array_pop($matches));  
            curl_setopt($ch, CURLOPT_URL, $url);  
            curl_setopt($ch, CURLOPT_HEADER, false);  
            $data = curl_exec($ch);

        }



        if ($data == false) {
            curl_close($ch);  
        }  
        @curl_close($ch);

        return $data;  
}
function getbgqrcode($imageDefault,$textDefault,$background,$filename="",$config=array()){
    //如果要看报什么错，可以先注释调这个header
    if(empty($filename)) header("content-type: image/png");
    //背景方法
    $backgroundInfo = getimagesize($background);

    $ext = image_type_to_extension($backgroundInfo[2], false);

    $backgroundFun = 'imagecreatefrom'.$ext;
    $background = $backgroundFun($background);
    $backgroundWidth = imagesx($background);  //背景宽度
    $backgroundHeight = imagesy($background);  //背景高度
    $imageRes = imageCreatetruecolor($backgroundWidth,$backgroundHeight);
    $color = imagecolorallocate($imageRes, 0, 0, 0);
    imagefill($imageRes, 0, 0, $color);
    imagecopyresampled($imageRes,$background,0,0,0,0,imagesx($background),imagesy($background),imagesx($background),imagesy($background));
    //处理了图片
    if(!empty($config['image'])){
        foreach ($config['image'] as $key => $val) {
            $val = array_merge($imageDefault,$val);
            $info = getimagesize($val['url']);
            $function = 'imagecreatefrom'.image_type_to_extension($info[2], false);
            if($val['stream']){
                //如果传的是字符串图像流
                $info = getimagesizefromstring($val['url']);
                $function = 'imagecreatefromstring';
            }
            $res = $function($val['url']);
            $resWidth = $info[0];
            $resHeight = $info[1];
            //建立画板 ，缩放图片至指定尺寸
            $canvas=imagecreatetruecolor($val['width'], $val['height']);
            imagefill($canvas, 0, 0, $color);
            //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
            imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'],$resWidth,$resHeight);
            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']) - $val['width']:$val['left'];
            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']) - $val['height']:$val['top'];

            //放置图像
            imagecopymerge($imageRes,$canvas, $val['left'],$val['top'],$val['right'],$val['bottom'],$val['width'],$val['height'],$val['opacity']);//左，上，右，下，宽度，高度，透明度
        }
    }

    //处理文字
    if(!empty($config['text'])){
        foreach ($config['text'] as $key => $val) {
            $val = array_merge($textDefault,$val);
            //  dump($val);
            list($R,$G,$B) = explode(',', $val['fontColor']);
            $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
            $val['left'] = $val['left']<0?$backgroundWidth- abs($val['left']):$val['left'];
            $val['top'] = $val['top']<0?$backgroundHeight- abs($val['top']):$val['top'];
            // dump($val['left']);dump($val['top']);
            imagettftext($imageRes,$val['fontSize'],$val['angle'],$val['left'],$val['top'],$fontColor,$val['fontPath'],$val['text']);
        }
    }


    //生成图片
    if(!empty($filename)){
        $res = imagejpeg ($imageRes,$filename,90);
        //保存到本地
        imagedestroy($imageRes);
    }else{
        imagejpeg ($imageRes);
        //在浏览器上显示
        imagedestroy($imageRes);
    }
}


 function https_request($url,$data = null){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

//请求函数
function send_post($url, $post_data,$method='POST') {
	$postdata = http_build_query($post_data);
	$options = array(
	  'http' => array(
		'method' => $method, //or GET
		'header' => 'Content-type:application/x-www-form-urlencoded',
		'content' => $postdata,
		'timeout' => 15 * 60 // 超时时间（单位:s）
	  )
	);
	$context = stream_context_create($options);
	$result = file_get_contents($url, false, $context);

	return $result;
}
/**
*求两个已知经纬度之间的距离,单位为千米
*@param lng1,lng2 经度
*@param lat1,lat2 纬度
*@return float 距离，单位千米
**/
//根据经纬度计算距离
function distance($lng1,$lat1,$lng2,$lat2){
	//将角度转为弧度
	$radLat1=deg2rad($lat1);
	$radLat2=deg2rad($lat2);
	$radLng1=deg2rad($lng1);
	$radLng2=deg2rad($lng2);
	$a=$radLat1-$radLat2;//两纬度之差,纬度<90
	$b=$radLng1-$radLng2;//两经度之差纬度<180
	$s=2*asin(sqrt(pow(sin($a/2),2)+cos($radLat1)*cos($radLat2)*pow(sin($b/2),2)))*6378.137;
	return $s;
}

//oss上传 
/* 
 *$fFiles:文件域 
 *$n：上传的路径目录 
 *$ossClient   
 *$bucketName 
 *$web:oss访问地址 
 *$isThumb:是否缩略图 
 */


function ossUpPic($fFiles,$n,$ossClient,$bucketName,$web,$isThumb=1){ 

	$fType=$fFiles['type']; 
    $back=array( 
        'code'=>0, 
        'msg'=>'', 
    ); 
    if(!in_array($fType, C('oss_exts'))){ 
        $back['msg']='文件格式不正确'; 
        return $back; 
        exit; 
    } 
    $fSize=$fFiles['size']; 
    if($fSize>C('max_upload_size')){
        $back['msg']=C('max_upload_size');
        $back['code']=1;
        return $back; 
        exit; 
    } 
    
    $fname=$fFiles['name']; 
    $ext=substr($fname,stripos($fname,'.')); 
     
    $fup_n=$fFiles['tmp_name']; 
    //$file_n=time().'_'.rand(100,999); 
    $file_n=substr(md5_file($fup_n), 8, 16); 
    $object = $n."/".date('Ymd')."/".$file_n.$ext;//目标文件名 
     
 
    if (is_null($ossClient)) exit(1);     
    $ossClient->uploadFile($bucketName, $object, $fup_n); 
       

    $back['url']=$web."/".$object; 
	if($isThumb==1){ 
        // 图片缩放，参考https://help.aliyun.com/document_detail/44688.html?spm=5176.doc32174.6.481.RScf0S  
        $back['url']=$web."/".$object.C('OSS_PICEND');  
    }else{
		$back['url']=$web."/".$object;
	}
    return $back; 
    exit;     
}
//oss上传 多图
/* 
 *$fFiles:文件域 
 *$n：上传的路径目录 
 *$ossClient   
 *$bucketName 
 *$web:oss访问地址 
 *$isThumb:是否缩略图 
 */ 
function ossUpPics($fFiles,$n,$ossClient,$bucketName,$web,$isThumb=0){ 
    

    $back=array( 
        'code'=>0, 
        'msg'=>'', 
    ); 
	if (is_null($ossClient)) {
		$back['msg']='未声明ossClient对象';
		return $back; 
	}  
	for($i=0;$i<count($fFiles['tmp_name']);$i++){
		$fType=$fFiles['type'][$i]; 
		if(!in_array($fType, C('oss_exts'))){
			continue;
		}
		$fSize=$fFiles['size'][$i]; 
		if($fSize>C('oss_maxSize')){ 
			continue;
		} 
		$fname=$fFiles['name'][$i]; 
		$ext=substr($fname,stripos($fname,'.')); 
		$fup_n=$fFiles['tmp_name'][$i]; 
		//$file_n=time().'_'.rand(100,999); 
		$file_n=substr(md5_file($fup_n), 8, 16); 
		$object = $n."/".date('Ymd')."/".$file_n.$ext;//目标文件名 
		$ossClient->uploadFile($bucketName, $object, $fup_n);
		
		if($isThumb==1){
			$arr[]=$web."/".$object.C('OSS_PICEND'); 
		}else{
			$arr[]=$web."/".$object;
		}
	}
	$back['url']=implode('|',$arr);
	$back['code']=1; 
    
    return $back; 
    exit;     
}
function xml_to_array( $xml )
{
    $reg = "/<(\\w+)[^>]*?>([\\x00-\\xFF]*?)<\\/\\1>/";
    if(preg_match_all($reg, $xml, $matches))
    {
        $count = count($matches[0]);
        $arr = array();
        for($i = 0; $i < $count; $i++)
        {
            $key= $matches[1][$i];
            $val = xml_to_array( $matches[2][$i] );  // 递归
            if(array_key_exists($key, $arr))
            {
                if(is_array($arr[$key]))
                {
                    if(!array_key_exists(0,$arr[$key]))
                    {
                        $arr[$key] = array($arr[$key]);
                    }
                }else{
                    $arr[$key] = array($arr[$key]);
                }
                $arr[$key][] = $val;
            }else{
                $arr[$key] = $val;
            }
        }
        return $arr;
    }else{
        return $xml;
    }
}

function UpImage($callBack = "image", $width = 100, $height = 100, $image = "")
{

    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width=' . $width . ' height="' . $height . '"  src="' . U('Upload/uploadpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
         <br><input size=50 type="text" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
}

function BatchImage($callBack = "image", $width = 100, $height = 100, $image = "")
{

    echo '<iframe scrolling="no" frameborder="0" border="0" width=100% style="min-height:120px"  onload="this.height=this.contentWindow.document.body.scrollHeight;" src="' . U('Upload/batchpic',
            array('Width' => $width, 'Height' => $height, 'BackCall' => $callBack)) . '"></iframe>
		<input size=80 type="hidden" ' . 'value = "' . $image . '"' . 'name="' . $callBack . '" id="' . $callBack . '">';
} 
 
// 返回json 
function backJson($code,$info){
	header("Content-type:text/json;charset=utf-8");
    $arr['status']=$code; 
    $arr['info']=$info; 
    print_r(json_encode($arr,JSON_UNESCAPED_UNICODE)); 
    exit; 
} 
 



/*
 * 函数：网站配置获取函数
 * @param  string $k      可选，配置名称
 * @return array          用户数据
*/
function setting($k = 'all')
{
    $cache = S($k);
    //如果缓存不为空直接返回
    if (null != $cache) {
        return $cache;
    }
    $data = '';
    $setting = M('setting');
    //判断是否查询全部设置项
    if ($k == 'all') {
        $setting = $setting->field('k,v')->select();
        foreach ($setting as $v) {
            $config[$v['k']] = $v['v'];
        }
        $data = $config;

    } else {
        $result = $setting->where("k='{$k}'")->find();
        $data = $result['v'];

    }
    //建立缓存
    if ($data) {
		if(isset($data['cacheTime']) && !empty($data['cacheTime'])){
			S($k, $data,$data['cacheTime']*60);
		}else{
			S($k, $data,600);
		}
        
    }
    return $data;
}

/**
 * 函数：格式化字节大小
 * @param  number $size 字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 */
function format_bytes($size, $delimiter = '')
{
    $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) {
        $size /= 1024;
    }
    return round($size, 2) . $delimiter . $units[$i];
}

/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password)
{
    /*
    *后续整强有力的加密函数
    */
    return md5('Q' . $password . 'W');

}


function getUserById($uid)
{
    return M('user')->where(['id'=>$uid])->find();
}


function list_arr($arr,$field='',$sort='desc')
{
    if(is_array($arr)){
        $a1 = $a2 = [];
        $a1 =array_column($arr,$field);
        switch ($sort)
        {
            case 'asc':
                asort($a1);
                break;
            case 'desc':
                arsort($a1);
                break;
        }

        foreach ($a1 as $k => $v)
        {
            $a2[] = &$arr[$k];  //
        }
        return $a2;
    }else{
        return false;
    }
}


function add_min_u($uid,$amount,$type,$info,$uniacid,$paytype=1)
{


    if($amount>0){

        if($paytype == 1){//增加
          //  echo $amount;die;
            M('user')->where(['id'=>$uid])->setInc($type,$amount);

        }else{//减少
            M('user')->where(['id'=>$uid])->setDec($type,$amount);

        }

        $u = getUserById($uid);



        $add['uid'] = $uid;
        $add['money'] = $amount;
        $add['balance'] = $u[$type];
        $add['type'] = $paytype;
        $add['addtime'] = time();
        $add['info'] = $info;
        $add['uniacid'] = $uniacid;
        $add['year'] = date('Y');
        $add['month'] = date('Ym');
        $add['day'] = date('Ymd');
        return M('caiwu')->add($add);
    }
}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length = 6, $type = 'string', $convert = 0)
{
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type])) {
        $type = 'string';
    }
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}

//获取所有的子级id
function category_get_sons($sid, &$array = array())
{
    //获取当前sid下的所有子栏目的id
    $categorys = M("category")->where("pid = {$sid}")->select();

    $array = array_merge($array, array($sid));
    foreach ($categorys as $category) {
        category_get_sons($category['id'], $array);
    }
    $data = $array;
    unset($array);
    return $data;

}


/**
 * 获取文章url地址
 * url结构：http://wwww.xxx.com/分类/子分类/子分类/id.html
 * 使用方法：模板中{:articleUrl(array('aid'=>$val['aid']))}
 *
 *
 * @param $data
 * @return $string
 */
function articleUrl($data)
{
    //如果数组为空直接返回空字符
    if (!$data) {
        return '';
    }
    //如果参数错误直接返回空字符
    if (!isset($data['aid'])) {
        return '';
    }

    $aid = (int)$data['aid'];

    //获取文章信息
    $article = M('article')->where(array('aid' => $aid))->find();
    //获取当前内容所在分类
    $category = M('category')->where(array('id' => $article['sid']))->find();
    //获取当前分类
    $categoryUrl = $category['dir'];
    //遍历获取当前文章所在分类的有上级分类并且组合url
    while ($category['pid'] <> 0) {
        $category = M('category')->where(array('id' => $category['pid']))->find();
        $categoryUrl = $category['dir'] . "/" . $categoryUrl;
        //如果上级分类已经无上级分类则退出
    }

    $categoryUrl = __ROOT__ . "/" . $categoryUrl;
    //组合文章url
    $articleUrl = $categoryUrl . '/' . $aid . ".html";
    return $articleUrl;

}









?>